﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Web.Script.Serialization;

namespace BeerManagementSystem
{
    class Beerbox
    {


        public Beerbox()
        {
            Thread t = new Thread(new ThreadStart(IsBeerboxOutdated));
            t.IsBackground = true;
            t.Start();
        }

        private void IsBeerboxOutdated()
        {
            var request = HttpWebRequest.Create("http://www.schmidtwoch.com/sites/default/bms-actions/updateBeerbox.php");
            request.Method = "POST";
            RequestState state = new RequestState(request);

            IAsyncResult result = request.BeginGetResponse(
                new AsyncCallback(UpdateBeerBox), state);

            ThreadPool.RegisterWaitForSingleObject(
                result.AsyncWaitHandle,
                new WaitOrTimerCallback(ScanTimeoutCallback),
                state,
                (30*1000), // 30 second timeout
                true
                );

        }

        private void UpdateBeerBox(IAsyncResult result)
        {
            RequestState state = (RequestState) result.AsyncState;
            WebRequest request = (WebRequest) state.Request;
            HttpWebResponse response = (HttpWebResponse) request.EndGetResponse(result);
            LinkedList<string> userInfo = new LinkedList<string>();
            Stream dataStream = response.GetResponseStream();
            if (dataStream != null)
            {
                string data = new StreamReader(dataStream).ReadToEnd();
                JavaScriptSerializer serializer = new JavaScriptSerializer();
                Dictionary<String, Object> post = (Dictionary<String, Object>)serializer.DeserializeObject(data);
                BeerboxItem item = new BeerboxItem();
                item.
            }
        }

        private static void ScanTimeoutCallback(object state, bool timedOut)
        {
            if (timedOut)
            {
                RequestState reqState = (RequestState)state;
                if (reqState != null)
                    reqState.Request.Abort();
            }
        }
    }

    internal class RequestState
    {
        public RequestState(WebRequest request)
        {
            this.Request = request;
        }

        public WebRequest Request { get; set; }
    }
}
